package com.tgy.leetcode;

import java.util.Stack;

/**
 * @Author: tgy
 * @Date: 12/1/20 9:51 AM
 *
 * https://leetcode-cn.com/problems/palindrome-linked-list/
 */
public class _234_回文链表_01 {

    public boolean isPalindrome(ListNode head) {

        if (head == null || head.next == null) {

            return true;
        }

        ListNode middle = findMiddle(head);

        Stack<Integer> stack = new Stack<>();

        // 把后面的链表入栈，避免判断是奇数还是偶数
        middle = middle.next;
        while (middle != null) {

            stack.push(middle.val);
            middle = middle.next;
        }

        ListNode headNode = head;
        while (!stack.isEmpty()) {

            if (stack.pop() != headNode.val) {

                return false;
            }
            headNode = headNode.next;
        }

        return true;
    }

    private ListNode findMiddle(ListNode head) {

        ListNode slowNode = head, fastNode = head;

        while (fastNode.next != null && fastNode.next.next != null) {

            slowNode = slowNode.next;
            fastNode = fastNode.next.next;
        }

        return slowNode;
    }
}
